#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>

#include "datamap.hpp"
#include "argparse.hpp"

using namespace std;

//const string OPTIONS_DEFAULT_DELIMITER = "\t"; 
const string OPTIONS_DEFAULT_MISSING_ID = "NA";
const bool   OPTIONS_DEFAULT_IS_VERBOSE = false;

struct Options {

  //string delimiter;
  //string delimiter_s;
  //string delimiter_l;

  string outputFile;
  string outputFile_s;
  string outputFile_l;

  string missingID;
  string missingID_s;
  string missingID_l;

  bool   isVerbose;
  string isVerbose_s;
  string isVerbose_l;

  Options():
    //delimiter(OPTIONS_DEFAULT_DELIMITER),
    //delimiter_s("d"),
    //delimiter_l("delimiter"),

    outputFile(""),
    outputFile_s("o"),
    outputFile_l("output"),

    missingID(OPTIONS_DEFAULT_MISSING_ID),
    missingID_s("m"),
    missingID_l("missing"),

    isVerbose(OPTIONS_DEFAULT_IS_VERBOSE),
    isVerbose_s("v"),
    isVerbose_l("verbose") {}

  void print() {
    cout << endl;
    cout << "Options:" << endl;
    //cout << " -" << delimiter_s << " / --" << delimiter_l << setw(10-delimiter_l.size()) << "" << "= " << delimiter << endl;
    cout << " -" << outputFile_s << " / --" << outputFile_l << setw(10-outputFile_l.size()) << "" << "= " << outputFile << endl; 
    cout << " -" << missingID_s << " / --" << missingID_l << setw(10-missingID_l.size()) << "" << "= " << missingID << endl;
    cout << " -" << isVerbose_s << " / --" << isVerbose_l << setw(10-isVerbose_l.size()) << "" << "= "; isVerbose ? cout << "YES" << endl : cout << "NO" << endl;
    cout << endl;
  }
};


int main(const int argc, char* const argv[]) {
  
  vector<string> files;
  
  int iter = 1;
  while ( iter < argc ) {
    string foo( argv[iter] );
    if ( foo.substr(0,1) == "-" ) {
      break;
    }
    files.push_back(foo);
    ++iter;
  }

  ArgParse parser(argc-iter+1,argv+iter-1);
  Options options;

  //parser.getArgument<string>(options.delimiter_s,options.delimiter_l,options.delimiter);
  parser.getArgument<string>(options.outputFile_s,options.outputFile_l,options.outputFile);
  parser.getArgument<string>(options.missingID_s,options.missingID_l,options.missingID);
  parser.getFlag(options.isVerbose_s,options.isVerbose_l,options.isVerbose);

  if ( options.isVerbose ) {
    options.print();
  }

  //stringstream ss(options.delimiter);
  //char delimiterAsChar;
  //ss >> delimiterAsChar;

  DataMap dataMap('\t',options.missingID);



  for ( size_t i = 0; i < files.size(); ++i) {
    dataMap.merge(files[i]);
  }
  
  if ( options.outputFile != "" ) {
    ofstream toFile;
    toFile.open(options.outputFile.c_str());
    dataMap.printToStream(toFile);
  } else {
    dataMap.printToStream(cout);
  }

  return ( EXIT_SUCCESS );
}
